package com.sbs.gaoxinqutoilet.base;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.jaeger.library.StatusBarUtil;
import com.sbs.gaoxinqutoilet.R;
import com.sbs.gaoxinqutoilet.entity.CheckToken;
import com.sbs.gaoxinqutoilet.entity.UserEntity;
import com.sbs.gaoxinqutoilet.http.HttpApis;
import com.sbs.gaoxinqutoilet.http.Request;
import com.sbs.gaoxinqutoilet.interfaces.Constant;
import com.sbs.gaoxinqutoilet.interfaces.Constants;
import com.sbs.gaoxinqutoilet.manager.ActivityManager;
import com.sbs.gaoxinqutoilet.myapp.MyApplication;
import com.sbs.gaoxinqutoilet.utils.GsonTools;
import com.sbs.gaoxinqutoilet.utils.HttpUtils;
import com.sbs.gaoxinqutoilet.utils.JsonUtil;
import com.sbs.gaoxinqutoilet.utils.LogUtils;
import com.sbs.gaoxinqutoilet.utils.PollingUtil;
import com.sbs.gaoxinqutoilet.utils.SPUtil;
import com.sbs.gaoxinqutoilet.utils.ToastUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportActivity;
import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

import static com.sbs.gaoxinqutoilet.utils.loading.LoadingDialog.cancelLoadingDialog;


//这个base 是用来开启fragmentation
public abstract class BaseActivity extends SupportActivity {

    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };

    private static final int PERMISSON_REQUESTCODE = 0;

    private boolean isNeedCheck = true;

    long timeInterval=1000*60*25;

    private Unbinder bind;
    protected Activity mActivity;
    private PollingUtil pollingUtil;
    private Runnable runnable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setSatusBar();
        Log.e("thisAc",this.getLocalClassName());
        mActivity=this;
        ActivityManager.getInstance().addActivity(this);
        initContentView(savedInstanceState);
        initView();
        initLogic();

        //每3秒打印一次日志
        pollingUtil = new PollingUtil(new Handler(getMainLooper()));
        runnable = new Runnable() {
            @Override
            public void run() {
                String token_data = SPUtil.getString(Constants.KEY_TOKEN, "");
                Log.e("token","token值:"+token_data);
                //check_token
                String url_check_token= HttpApis.check_token+token_data;
//        HashMap<String, String> map = new HashMap<>();
//        map.put("token", token_data);
                HttpUtils.requestGet(BaseActivity.this, url_check_token,  new Request(){
                    @Override
                    public void success(String jsonStr) {
                        super.success(jsonStr);
                        Log.e("jsonStr","jsonStr值:"+jsonStr);
                        CheckToken checkToken = JsonUtil.json2Bean(jsonStr, CheckToken.class);
                        if(checkToken==null||!"1".equals(checkToken.getState())){
                            //重新登录--
                            //访问重新登录接口
                            //姓名
                            String login_name = SPUtil.getString(Constants.KEY_USERNAME, "");
                            //登录密码
                            String login_pass=SPUtil.getString(Constant.KEY_USERPWD, "");

                            getReLogin(login_name,login_pass);

                        }
                    }

                    @Override
                    public void error(String error) {
                        super.error(error);
                        Log.e("jsonStr","error值:"+error);
                    }
                });
            }
        };
        pollingUtil.startPolling(runnable, timeInterval, true);

    }

    private void getReLogin(String login_name, String login_pass) {
        String mBuyUrl = HttpApis.login;
        HashMap<String ,String> map=new HashMap<>();
        map.put("name", login_name);
        map.put("password", login_pass);

        HttpUtils.requestPost(this, mBuyUrl, map, new Request(){
            @Override
            public void success(String jsonStr) {
                super.success(jsonStr);
                LogUtils.i("loginAccount", "success: "+jsonStr);

                UserEntity loginEntity = GsonTools.changeGsonToBean(jsonStr, UserEntity.class);
                //数据解析
                if (loginEntity != null) {
                    //姓名
                    SPUtil.putString(Constants.KEY_USERNAME, login_name);
                    //不保存登录密码
                    SPUtil.putString(Constant.KEY_USERPWD, login_pass);
                    //login  token  每次请求都要带有这个token
                    SPUtil.putString(Constants.KEY_TOKEN, loginEntity.getToken());
                    LogUtils.i("show_token_data",loginEntity.getToken());
                    MyApplication.setUserEntity(loginEntity);
                    SPUtil.putBeanValue(Constants.KEY_USER, loginEntity);

                }
                cancelLoadingDialog();
            }

            @Override
            public void error(String error) {
                super.error(error);

            }
        });
    }


    private void setSatusBar() {
        //状态栏沉浸
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_300));
        //StatusBarUtils.setLightMode(this);
    }

    protected abstract void initContentView(Bundle savedInstanceState) ;
    protected abstract void initView();

    protected abstract void initLogic();

    @Override
    public void onBackPressedSupport() {
        super.onBackPressedSupport();
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        // 设置横向(和安卓4.x动画相同)
        return new DefaultHorizontalAnimator();
    }
    //Toast显示
    protected void showShortToast(String string) {
        ToastUtils.showShortToast(this, string);
    }

    protected void showShortToast(int stringId) {
        ToastUtils.showShortToast(this, stringId);
    }


    //软键盘监听
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }

//        mGestureDetector.onTouchEvent(ev);
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 隐藏软件盘方法
     *
     * @param token
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            if (isNeedCheck) {
                checkPermissions(needPermissions);
            }
        }
    }

    private void checkPermissions(String... permissions) {
        try {
            if (Build.VERSION.SDK_INT >= 23
                    && getApplicationInfo().targetSdkVersion >= 23) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                    Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class,
                            int.class});

                    method.invoke(this, array, PERMISSON_REQUESTCODE);
                }
            }
        } catch (Throwable e) {
        }
    }

    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23){
            try {
                for (String perm : permissions) {
                    Method checkSelfMethod = getClass().getMethod("checkSelfPermission", String.class);
                    Method shouldShowRequestPermissionRationaleMethod = getClass().getMethod("shouldShowRequestPermissionRationale",
                            String.class);
                    if ((Integer)checkSelfMethod.invoke(this, perm) != PackageManager.PERMISSION_GRANTED
                            || (Boolean)shouldShowRequestPermissionRationaleMethod.invoke(this, perm)) {
                        needRequestPermissonList.add(perm);
                    }
                }
            } catch (Throwable e) {

            }
        }
        return needRequestPermissonList;
    }

    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }

    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     *
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     *  启动应用的设置
     *
     * @since 2.5.0
     *
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(pollingUtil!=null&&runnable!=null){
            pollingUtil.endPolling(runnable);
        }

    }
}
